﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace MVVMFramework.View
{
    public class DefaultValueToVisibilityConverter : ToVisibilityConverterBase
    {
        protected override object TryConvert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Visibility convertedValue = UseHidden ? Visibility.Hidden : Visibility.Collapsed;

            // null is default value
            if (value == null)
            {
                convertedValue = Visibility.Visible;
            }
            else
            {
                Type valueType = value.GetType();
                object defaultValue = GetDefaultValue(valueType);
                if (object.Equals(value, defaultValue))
                    convertedValue = Visibility.Visible;
            }

            return convertedValue;
        }

        protected override object TryConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!(value is Visibility))
                throw new ConverterException("Unexpected value type");

            Visibility visibility = (Visibility)value;
            if (visibility == Visibility.Visible)
                return GetDefaultValue(targetType);

            throw new ConverterException("Undefined conversion");
        }
    }
}
